package com.sa.satoken.common.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import com.sa.satoken.common.factory.YamlPropertySourceFactory;
import com.sa.satoken.common.handler.GlobalExceptionHandler;
import com.sa.satoken.common.service.StpInterfaceImpl;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

/**
 * @author Architecture Station
 * @version 1.0
 * @website 
 */
@AutoConfiguration
@PropertySource(value = "classpath:satoken-common.yaml",factory = YamlPropertySourceFactory.class)
public class SaTokenAutoConfiguration implements WebMvcConfigurer {

    @Bean
    public StpInterface stpInterface(){
        return new StpInterfaceImpl();
    }

    @Bean
    public GlobalExceptionHandler globalExceptionHandler(){
        return new GlobalExceptionHandler();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }

    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }

    // 注册 Sa-Token 拦截器，打开注解式鉴权功能
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        //registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**");

        registry.addInterceptor(new SaInterceptor(handle -> {
            SaRouter
                    .match("/**")
                    .notMatch(excludePaths())
                    .check(r -> StpUtil.checkLogin());
        })).addPathPatterns("/**");
    }

    // 动态获取哪些 path 可以忽略鉴权
    public List<String> excludePaths() {
        // 此处仅为示例，实际项目你可以写任意代码来查询这些path
        return Arrays.asList("/api/auth/login", "/api/users/login");
    }
}


